package com.naxiangfish.cn.naxiangfish;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.request.GetRequest;
import com.lzy.okserver.OkDownload;
import com.lzy.okserver.download.DownloadListener;
import com.lzy.okserver.download.DownloadTask;
import com.lzy.okserver.task.XExecutor;
import com.naxiangfish.cn.R;
import com.naxiangfish.cn.adapter.DownLoadeAdapter;
import com.naxiangfish.cn.been.DownLoadeBeen;
import com.naxiangfish.cn.constant.ConstantUtils;
import com.naxiangfish.cn.constant.UriContent;
import com.naxiangfish.cn.utils.ToastMake;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

public class PayActivity extends BaseActivity implements XExecutor.OnAllTaskEndListener {

    private static final int REQUEST_PERMISSION_STORAGE = 10000;
    private ProgressBar        mProgressBar;
    private DownloadTask       task;
    private RecyclerView       mRecyclerView;
    private SmartRefreshLayout mSmartRefreshLayout;

    private Handler mHandler = new Handler(Looper.getMainLooper()) {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mSmartRefreshLayout.finishRefresh();
                    ToastMake.showToast("刷新完成了");
                    break;
                case 2:
                    mSmartRefreshLayout.finishLoadmore();
                    ToastMake.showToast("没有更多了");
                    break;
            }
        }
    };
    private DownLoadeAdapter mLoadeAdapter;

    private List<DownLoadeBeen> mList = new ArrayList<>();
    private OkDownload okDownload;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentViewShow(R.layout.activity_pay);
        setWindShowStyle(ConstantUtils.RELEATSHOW);
        setTitleText("第二个界面");
        checkSDCardPermission();

        mProgressBar = (ProgressBar) findViewById(R.id.pbProgress);
        mRecyclerView = (RecyclerView) findViewById(R.id.recycleview);


        //进来首页首先获取本地已经下载的文件
        // 写法一：从内存中获取
        if (OkDownload.getInstance().hasTask(UriContent.downLoadeFile)) {
            task = OkDownload.getInstance().getTask(UriContent.downLoadeFile)//
                    .register(new LogDownloadListener());
        }

        if (task != null) {
            mProgressBar.setMax(10000);
            mProgressBar.setProgress((int) (task.progress.fraction * 10000));
        }


        mSmartRefreshLayout = (SmartRefreshLayout) findViewById(R.id.smartlayout);
        resycelViewUse();


        //下拉刷新
        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {

                        Message message = Message.obtain();
                        message.what = 1;
                        mHandler.sendMessage(message);
                    }
                }, 2000);
            }
        });

        //上拉加载更多
        mSmartRefreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {

                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Message message = Message.obtain();
                        message.what = 2;
                        mHandler.sendMessage(message);
                    }
                }, 2000);
            }
        });

    }

    private void resycelViewUse() {

        DownLoadeBeen been1 = new DownLoadeBeen();
        been1.setImageUri("http://jzvd-pic.nathen.cn/jzvd-pic/00b026e7-b830-4994-bc87-38f4033806a6.jpg");
        been1.setName("第一个");
        been1.setDownUri("http://jzvd.nathen.cn/c494b340ff704015bb6682ffde3cd302/64929c369124497593205a4190d7d128-5287d2089db37e62345123a1be272f8b.mp4");
        been1.setText("开始下载");

        DownLoadeBeen been2 = new DownLoadeBeen();
        been2.setImageUri("http://jzvd-pic.nathen.cn/jzvd-pic/1d935cc5-a1e7-4779-bdfa-20fd7a60724c.jpg");
        been2.setName("第二个");
        been2.setText("开始下载");
        been2.setDownUri("http://jzvd.nathen.cn/63f3f73712544394be981d9e4f56b612/69c5767bb9e54156b5b60a1b6edeb3b5-5287d2089db37e62345123a1be272f8b.mp4");
        DownLoadeBeen been3 = new DownLoadeBeen();
        been3.setImageUri("http://jzvd-pic.nathen.cn/jzvd-pic/a019ffc1-556c-4a85-b70c-b1b49811d577.jpg");
        been3.setName("第三个");
        been3.setDownUri("http://jzvd.nathen.cn/b201be3093814908bf987320361c5a73/2f6d913ea25941ffa78cc53a59025383-5287d2089db37e62345123a1be272f8b.mp4");
        been3.setText("开始下载");

        DownLoadeBeen been4 = new DownLoadeBeen();
        been4.setImageUri("http://wx2.sinaimg.cn/mw690/006ZrXHXgy1fsr074hxtyg308w07xu0x.gif");
        been4.setName("第四个");
        been4.setDownUri("http://jzvd.nathen.cn/d2438fd1c37c4618a704513ad38d68c5/68626a9d53ca421c896ac8010f172b68-5287d2089db37e62345123a1be272f8b.mp4");
        been4.setText("开始下载");

        DownLoadeBeen been5 = new DownLoadeBeen();
        been5.setImageUri("http://jzvd-pic.nathen.cn/jzvd-pic/f03cee95-9b78-4dd5-986f-d162c06c385c.png");
        been5.setName("第五个");
        been5.setDownUri("http://jzvd.nathen.cn/25a8d119cfa94b49a7a4117257d8ebd7/f733e65a22394abeab963908f3c336db-5287d2089db37e62345123a1be272f8b.mp4");
        been5.setText("开始下载");

        DownLoadeBeen been6 = new DownLoadeBeen();
        been6.setImageUri("http://jzvd-pic.nathen.cn/jzvd-pic/e7ea659f-c3d2-4979-9ea5-f993b05e5930.png");
        been6.setName("第六个");
        been6.setDownUri("http://jzvd.nathen.cn/7512edd1ad834d40bb5b978402274b1a/9691c7f2d7b74b5e811965350a0e5772-5287d2089db37e62345123a1be272f8b.mp4");
        been6.setText("开始下载");

        DownLoadeBeen been7 = new DownLoadeBeen();
        been7.setImageUri("");
        been7.setName("第七个");
        been7.setDownUri("http://jzvd.nathen.cn/c6e3dc12a1154626b3476d9bf3bd7266/6b56c5f0dc31428083757a45764763b0-5287d2089db37e62345123a1be272f8b.mp4");
        been7.setText("开始下载");

        mList.add(been1);
        mList.add(been2);
        mList.add(been3);
        mList.add(been4);
        mList.add(been5);
        mList.add(been6);
        mList.add(been7);



        okDownload = OkDownload.getInstance();
        mLoadeAdapter = new DownLoadeAdapter(mList,PayActivity.this);

        mLoadeAdapter.updateData(DownLoadeAdapter.TYPE_ING);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(PayActivity.this));
        mRecyclerView.setAdapter(mLoadeAdapter);
        okDownload.addOnAllTaskEndListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 写法一：从内存中获取
        //        if (OkDownload.getInstance().hasTask(UriContent.downLoadeFile)) {
        //            task = OkDownload.getInstance().getTask(UriContent.downLoadeFile)//
        //                    .register(new LogDownloadListener());
        //        }
        //        mProgressBar.setProgress((int) (task.progress.fraction * 10000));
    }

    /**
     * 检查SD卡权限
     */
    protected void checkSDCardPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //获取权限
            } else {
                Toast.makeText(this, "权限被禁止，无法下载文件！", Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void dowmloade(View view) {
        ToastMake.showToast("开始下载");
        //        OkGo.<File>get("http://osstest.fk.houdask.com/sys/v/18/08/4e2a1d263a814aa386c28c1dd5cac0e3.mp4")//
        //                .tag(this)
        //                .execute(new FileCallback("OkGo.apk") {
        //
        //                    @Override
        //                    public void onStart(Request<File, ? extends Request> request) {
        ////                        btnFileDownload.setText("正在下载中");
        //
        //                        System.out.println("下载中....");
        //                    }
        //
        //                    @Override
        //                    public void onSuccess(Response<File> response) {
        ////                        btnFileDownload.setText("下载完成"+response.body());
        //                        System.out.println("下载完成");
        //                    }
        //
        //                    @Override
        //                    public void onError(Response<File> response) {
        ////                        btnFileDownload.setText("下载出错");
        //                        System.out.println("下载出错");
        //                    }
        //
        //                    @Override
        //                    public void downloadProgress(Progress progress) {
        //                        System.out.println(progress);
        //                    }
        //                });


        //这里只是演示，表示请求可以传参，怎么传都行，和okgo使用方法一样

        //这里第一个参数是tag，代表下载任务的唯一标识，传任意字符串都行，需要保证唯一,我这里用url作为了tag
        if (task == null) {
            GetRequest<File> request = OkGo.<File>get(UriContent.downLoadeFile);//
//                    .headers("aaa", "111")//
//                    .params("bbb", "222");
            task = OkDownload.request(UriContent.downLoadeFile, request)//
                    //                    .priority(priority)//
                    // .extra1(apk)//
                    //这里设置保存的视频文件，以及视频的名称
                    .folder(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES).getPath())
                    .fileName("赵航播放的.mp4")
                    .save()//
                    .register(new LogDownloadListener());

        }
        task.start();
    }

    //停止下载
    public void stopdown(View view) {

        task.pause();
    }

    //继续下载
    public void contiundown(View view) {

        // 写法一：从内存中获取
        if (OkDownload.getInstance().hasTask(UriContent.downLoadeFile)) {
            task = OkDownload.getInstance().getTask(UriContent.downLoadeFile)//
                    .register(new LogDownloadListener());
        }
        task.start();

    }

    //删除重新下载
    public void deletdown(View view) {
        task.restart();
    }

    @Override
    public void onAllTaskEnd() {
       ToastMake.showToast("所有任务已经结束了");
    }

    private class LogDownloadListener extends DownloadListener {
        public LogDownloadListener() {
            super("LogDownloadListener");
        }

        @Override
        public void onStart(Progress progress) {
            System.out.println("开始下载了");
            mProgressBar.setMax(10000);
            mProgressBar.setProgress((int) (progress.fraction * 10000));
        }

        @Override
        public void onProgress(Progress progress) {
            System.out.println("当前的下载进度" + progress);
            mProgressBar.setProgress((int) (progress.fraction * 10000));
        }

        @Override
        public void onError(Progress progress) {
            System.out.println("当前下载失败的进度" + progress);
            progress.exception.printStackTrace();
        }

        @Override
        public void onFinish(File file, Progress progress) {
            mProgressBar.setProgress((int) (progress.fraction * 10000));
            System.out.println("当前下载结束的文件的路径" + file.getAbsolutePath() + "\n" + "下载完成后的进度" + progress);
        }

        @Override
        public void onRemove(Progress progress) {
            System.out.println("onRemove" + progress);
        }
    }


    //批量下载
    public void alldown(View view){
        checkSDCardPermission();



    }



    @Override
    public void onBackPressed() {
        super.onBackPressed();
        OkGo.getInstance().cancelTag(UriContent.downLoadeFile);

        okDownload.removeOnAllTaskEndListener(this);
//        mLoadeAdapter.unRegister();
        finish();
    }

}
